package test.lyj.model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import test.lyj.tool.Tool;


import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class NetThread extends TimerTask {
	private List<NameValuePair> params;
	private ProgressDialog pd;
	private Handler messageHandler;
	public boolean stopFlag = false;
	private Context c;
	// 最大连接时间
	protected int maxLinedSecond = 20;
	private int linkedTimes=0;//当前连接秒数
	
	public NetThread(Context c, Handler messageHandler,
			Map<String, String> map, String pdTitle) {
		this.pd = startProgress(c, pdTitle);
		this.messageHandler = messageHandler;
		this.c=c;
		suitMap2Params(map);
		Timer timer = new Timer();
		timer.schedule(this, 50);
	}
	@Override
	public void run() {
		new Thread() {
			public void run() {
				if(!isconnected(c)){
					stopFlag=true;
					Message message = new Message();
					message.what = Tool.TIMER_TASK_TIMEOUT;
					Bundle b = new Bundle();
					b.putString(Tool.TIMER_TASK_RESULT, "无法获得网络,请检查网络是否通畅.");
					message.setData(b);
					messageHandler.sendMessage(message);
					if(pd!=null)
					pd.dismiss();
				}
				try {
					synchronized (this) {
						String result = getResponse(params);
						if (!stopFlag) {
							maxLinedSecond = 0;
							stopFlag = true;
							Message message = new Message();
							message.what = Tool.TIMER_TASK_COMPELETE;
							Bundle b = new Bundle();
							b.putString(Tool.TIMER_TASK_RESULT, result);
							message.setData(b);
							messageHandler.sendMessage(message);
							if(pd!=null)
							pd.dismiss();
						}
					}
				} catch (Exception e) {
					Message message = new Message();
					message.what = Tool.TIMER_TASK_TIMEOUT;
					Bundle b = new Bundle();
					b.putString(Tool.TIMER_TASK_RESULT, "服务器连接中断,网络超时。");
					message.setData(b);
					messageHandler.sendMessage(message);
					if(pd!=null)
					pd.dismiss();
				}
			}
		}.start();
		try {
			while (!stopFlag && maxLinedSecond > 0) {
				Message message = new Message();
				message.what = Tool.TIMER_TASK_LINKEDTIME;
				Bundle b = new Bundle();
				b.putString(Tool.TIMER_TASK_RESULT, String
						.valueOf(linkedTimes));
				message.setData(b);
				messageHandler.sendMessage(message);
				Thread.sleep(1000);
				maxLinedSecond--;
				linkedTimes++;

			}
			if (!stopFlag) {
				stopFlag = true;
				Thread.sleep(200);
				Message message = new Message();
				message.what = Tool.TIMER_TASK_TIMEOUT;
				Bundle b = new Bundle();
				b.putString(Tool.TIMER_TASK_RESULT, "服务器连接中断,网络超时。");
				message.setData(b);
				messageHandler.sendMessage(message);
				if(pd!=null)
				pd.dismiss();
			}

		} catch (InterruptedException e) {
			e.printStackTrace();
			if(pd!=null)
			pd.dismiss();
		}
	}
	/**
	 * 返回统一的网络滚动提示条
	 * @param c
	 * @param title
	 * @return
	 */
	private static ProgressDialog startProgress(Context c, String title) {
		if (Tool.isBlank(title))
			title = "数据加载,请稍后...";
		ProgressDialog pd = ProgressDialog.show(c, null, title, true, false);
		
		return pd;
	}
	/**
	 * 组装数据,调用网络连接时候用的是特殊的数据格式(BasicNameValuePair)
	 * @param map
	 */
	private void suitMap2Params(Map<String, String> map) {
		params = new ArrayList<NameValuePair>();
		Collection<Entry<String, String>> mapEntry = map.entrySet();
		for (Iterator<Entry<String, String>> iterator = mapEntry.iterator(); iterator
				.hasNext();) {
			Entry<String, String> entry = (Entry<String, String>) iterator
					.next();
			params.add(new BasicNameValuePair(String.valueOf(entry.getKey()),
					String.valueOf(entry.getValue())));
		}
	}
	/**
	 * 判断手机是否开启网络
	 * @param c
	 * @return
	 */
	private boolean isconnected(Context c){
		boolean netSataus = false;
        ConnectivityManager cwjManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);

        cwjManager.getActiveNetworkInfo();

        if (cwjManager.getActiveNetworkInfo() != null) {
            netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
        }
        return netSataus;
	}
	
	/**
	 * 访问服务器
	 * 联网的主要方法
	 * @param parameterMap
	 *            参数map
	 * @return 得到服务器返回值。
	 */
	private String getResponse(List<NameValuePair> params) {
		String netUrl = Tool.SERVICE_URL;
		HttpPost httpRequest = new HttpPost(netUrl);
		try {
			httpRequest.setEntity(new UrlEncodedFormEntity(params, "GBK"));
			// httpRequest.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequest);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = httpResponse.getEntity();
				String r = EntityUtils.toString(entity);
				return Tool.Base64decode(r);
			
			} else {
				//return httpResponse.getStatusLine().toString();
				throw new Exception("网络连接失败");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return "网络连接失败!";
		} catch (IOException e) {
			e.printStackTrace();
			return "数据传输错误!";
		} catch (Exception e) {
			e.printStackTrace();
			return "服务器连接中断,网络超时。";
		} finally {
			try {
				httpRequest.clone();
			} catch (CloneNotSupportedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
